﻿/*----------------------------------------------------------------
// Copyright (C) 2011 苏富特健康科技
// 版权所有。 
//
// 文件名：AuthorizeAttribute.cs
// 文件功能描述：是否登录判断
//
// 
// 创建标识：2012-10-24 zhangqiang
//
// 修改标识：
// 修改描述：
//
//
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHelper.SessionHandler;
using System.Configuration;
using System.Reflection;

namespace WebPlatform.FiltersAndSession
{
    [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true,
    AllowMultiple = true)]
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            Sessions session = MvcApplication.Container.Resolve<Sessions>();
            UserSession userSession = session.User;
            if (null == userSession || userSession.UserID == 0)
            {
                Uri uri = filterContext.HttpContext.Request.Url;
                UriBuilder uriBuilder = new UriBuilder()
                {
                    Host = uri.Host,
                    Path = "/Login/Index",
                    Port = uri.Port,
                    Fragment = uri.Fragment,
                    Scheme = uri.Scheme
                };
                if (filterContext.HttpContext.Request.IsAjaxRequest())//ajax请求处理
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new
                        {
                            Error = "NotAuthorized",
                            RedirectUrl = uriBuilder.Uri.ToString(),
                            IsSuccess = false
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {

                    filterContext.HttpContext.Response.Write("<script type='text/javascript'>top.location.href='" + uriBuilder.Uri.ToString() + "'</script>");
                    filterContext.HttpContext.Response.End();
                    filterContext.Result = new EmptyResult();
                }
            }
        }


    }
}